package com.ribben.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

public class WeightClusterRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties ndp;
    @Autowired
    private NacosServiceManager nsm;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        //用于获取当前要访问的服务名
        BaseLoadBalancer bl= (BaseLoadBalancer) this.getLoadBalancer();
        String name = bl.getName();
        System.out.println("-------------"+name);
        //获取nacos微服务发现的api对象
        NamingService ns=nsm.getNamingService(ndp.getNacosProperties());
        //通过条件做服务发现
        try {
//            Instance instance = ns.selectOneHealthyInstance(name,ndp.getGroup(),
//                    Arrays.asList(ndp.getClusterName()));

            List<Instance> instances=ns.selectInstances(name,ndp.getGroup(),true);
            List<Instance> clusterInstances=instances.stream().filter(ins->ins.getClusterName().equals(ndp.getClusterName())).collect(Collectors.toList());
            clusterInstances=clusterInstances==null||clusterInstances.size()<=0? instances:clusterInstances;
            if(instances!=null&&instances.size()>0){
                Instance instance = MyRandomWeight.getByRandomWeight(clusterInstances);
                return new NacosServer(instance);
            }

        } catch (NacosException e) {
           e.printStackTrace();
        }

        return null;
    }

    static class MyRandomWeight extends Balancer{
        //Balancer中的getHostByRandomWeight方法为protect,无法直接调用
        public static Instance getByRandomWeight(List<Instance> hosts){
            return Balancer.getHostByRandomWeight(hosts);
        }
    }



}
